<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Services;

use App\Enums\CheckStatusEnum;
use App\Enums\UserIdentityEnum;
use App\Models\UserCountDaily;
use App\Models\UserProfile;

class CountUserService
{
    public function countUsers()
    {
        $date = date('Y-m-d', time());
        $flowUserCount = UserProfile::query()
            ->doesntHave('check')
            ->where('identity', UserIdentityEnum::FLOW_USER)
            ->where('check_status', CheckStatusEnum::CHECK_ADOPT)
            ->count();

        $houserCount = UserProfile::query()
            ->where('identity', UserIdentityEnum::HOUSER)
            ->doesntHave('check')
            ->where('check_status', CheckStatusEnum::CHECK_ADOPT)
            ->count();

        $normalCount = UserProfile::query()
            ->doesntHave('check')
            ->where('identity', UserIdentityEnum::NORMAL)
            ->where('check_status', CheckStatusEnum::CHECK_ADOPT)
            ->count();

        if (UserCountDaily::query()->where('date', $date)->exists()) {
            UserCountDaily::query()->where('date', $date)
                ->update([
                    'date' => $date,
                    'flow_user_count' => $flowUserCount,
                    'houser_count' => $houserCount,
                    'normal_count' => $normalCount,
                ]);
        } else {
            UserCountDaily::query()->create([
                'date' => $date,
                'flow_user_count' => $flowUserCount,
                'houser_count' => $houserCount,
                'normal_count' => $normalCount,
            ]);
        }
    }
}
